import { PlusCircleOutlined } from "@ant-design/icons"
import { Button, Card, Input, Space, Tooltip, Typography } from "antd"
import { TextAreaProps } from "antd/lib/input"
import styles from "./index.module.less";
import { useEffect, useRef, useState } from "react";
import { AppConsumerFunction } from "@/services/common/functioninterface";

const { TextArea } = Input
const { Text } = Typography

export interface KeyValuePair {
  idx: number
  key: string,
  value: string
}

export interface VariableTempalteProp {
  // 标题
  title?: string
  // 模板内容
  templateContent?: string
  // 变量匹配模式，正则表达式
  variableRegex?: string
  // 是否作为正则表达式模式串匹配
  isRegex?: boolean
  textAreaProp?: TextAreaProps,
  // 点击填充事件
  onClickFill?: AppConsumerFunction<string>
  
}

const variableReg = "\\$\\{([^}]+)\\}"

// 看下是否需要直接使用form表单来存储编辑状态数据
export default function VariableTempalte(props: VariableTempalteProp) {
  const compProps: VariableTempalteProp = {
    title: '未命名标题',
    templateContent: "",
    variableRegex: variableReg,
    isRegex: true,
    textAreaProp: {},
    ...props
  }

  const [errorInfo, setErrorInfo] = useState<string>()
  const [keyValueList, setKeyValueList] = useState<any>([])
  const [reg, setReg] = useState<string>(variableReg)

  const inputRef = useRef<any>({})

  const getVariableList = (prop: VariableTempalteProp): KeyValuePair[] => {
    if (!prop.templateContent || prop.templateContent.length === 0) {
      setErrorInfo("模板内容为空")
      return []
    }
    if (!prop.variableRegex || prop.variableRegex.length === 0) {
      setErrorInfo("模板匹配变量为空")
      return []
    } else {
      setErrorInfo("")
    }
    const re = new RegExp(prop.variableRegex, "g")
    const matches = prop.templateContent?.matchAll(re);
    if (!matches) {
      return []
    }
    const res = [...matches?.map((item, idx) => {
      return {key: item[0], value: item[1], idx: idx}
    })]
    setKeyValueList(res)
    return res
  }

  const formMapToList = (kvMap: any) => {
    const res = []
    // eslint-disable-next-line guard-for-in
    for (let k in kvMap) {
      res.push(kvMap[k])
    }
    return res;
  }

  const getFillTemplateContent = (): string => {
    let resString: string = compProps.templateContent ? compProps.templateContent : ""
    keyValueList?.forEach((item: any) => {
      resString = resString?.replace(item.key, inputRef.current[item.idx])
    })
    return resString;
  }

  const handleClickFill = () => {
    const res = getFillTemplateContent()
    if (compProps.onClickFill) {
      compProps.onClickFill(res)
    }
  }

  useEffect(() => {
    getVariableList({...compProps, variableRegex: reg})
  }, [reg])

  return <Card className={styles['container']} 
            title={compProps.title}
            extra={<>
              <Text style={{color: 'red'}}>{errorInfo}</Text>
              <Tooltip title="填入">
                <Button icon={<PlusCircleOutlined />} type="text" onClick={() => {handleClickFill()}}></Button>
              </Tooltip>
            </>}>
            <TextArea
              value={compProps.templateContent}
              {...compProps.textAreaProp}
            >
            </TextArea>
            <Space direction="vertical">
              <Space>
                <Text>变量匹配模式:</Text>
                <Button type="link" onClick={() => {setReg(variableReg)}}>重置</Button>
              </Space>
              <Input 
                value={reg}
                onChange={(e) => {setReg(e.target.value)}}
              >
              </Input>
              <Space direction="vertical">
                {
                  keyValueList?.map((item: any) => {
                    return <Space key={item.idx}>
                      <Text>{item.key}</Text>
                      <Input onChange={(e) => {inputRef.current[item.idx] = e.target.value}}></Input> 
                    </Space>
                  })
                }
              </Space>
              <Button onClick={() => {handleClickFill()}} type="primary" style={{width: '100%'}}>填入</Button>
            </Space>
          </Card>

}